import {Module} from "vuex";

import {
  accountLoginRequest,
  requestUserInfoById,
} from "@/service/login/login";
import localCache from "@/utils/cache";
import {mapMenusToRoutes} from "@/utils/map-menus";
import router from "@/router";

import {IAccount} from "@/service/login/type";
import {ILoginState} from "./types";
import {IRootState} from "../types";

const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: "",
      userInfo: {},
      userMenus: [],
      permissions: [],
      privilege: ""
    };
  },
  getters: {},
  mutations: {
    changeToken(state, token: string) {
      state.token = token;
      localCache.setCache("token", token);
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo;
      const routes = mapMenusToRoutes();
      routes.forEach((route) => {
        router.addRoute("main", route);
      });
    },
    changePrivilege(state, privilege) {
      state.privilege = privilege;
    }
  },
  actions: {
    async accountLoginAction({commit, dispatch}, payload: IAccount) {
      // 1.实现登录逻辑
      const loginResult = await accountLoginRequest(payload);
      const {id, token} = loginResult.data;
      commit("changeToken", token);

      // 2.请求用户信息
      const userInfoResult = await requestUserInfoById(id);
      const userInfo = userInfoResult.data;
      commit("changeUserInfo", userInfo);
      localCache.setCache("privilege", userInfo.user_privilege ?? "viewer");
      localCache.setCache("userInfo", userInfo);
      // 4.跳到首页
      router.push("/main");
    },

    loadLocalLogin({commit, dispatch}) {
      const token = localCache.getCache("token");
      if (token) {
        commit("changeToken", token);
      }
      const userInfo = localCache.getCache("userInfo");
      if (userInfo) {
        commit("changeUserInfo", userInfo);
      }
      const privilege = localCache.getCache('privilege')
      if (privilege) {
        commit("changePrivilege", privilege)
      }
    }
  }
};

export default loginModule;
